﻿using System.Web;
using System.Data;
using System;
using System.Text;
using System.Web.Script.Serialization;

namespace Pcb.Common
{
    /// <summary>
    /// json数据
    /// </summary>
    public static class _Json
    {        
        #region 静态方法

        /// <summary>
        /// 把对象集合序列化 JSON 字符串 
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="items">对象实体</param>
        /// <returns>JSON字符串</returns>
        public static string GetJson<T>(System.Collections.Generic.IEnumerable<T> items) where T : class, new()
        {
            if (items == null)
                throw new NullReferenceException("序列化对象不能为null!");
            System.Text.StringBuilder st = new System.Text.StringBuilder();
            try
            {
                StringBuilder sb = new StringBuilder();
                var jsonSerializer = new JavaScriptSerializer();
                jsonSerializer.Serialize(items, sb);

                string str = sb.ToString();
                str = System.Text.RegularExpressions.Regex.Replace(str, @"\\/Date\((\d+)\)\\/", match => { DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return dt.ToString("yyyy-MM-dd HH:mm:ss"); });

                return str;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 把对象序列化 JSON 字符串 
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象实体</param>
        /// <returns>JSON字符串</returns>
        public static string GetJson<T>(this T obj) where T : class, new()
        {
            if (obj == null)
                throw new NullReferenceException("序列化对象不能为null!");
            try
            {
                JavaScriptSerializer seria = new JavaScriptSerializer();
                return seria.Serialize(obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

    }

}
